package com.example.qihuibao.widget.dialog

import android.content.DialogInterface
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.module.main.MainViewModel
import com.example.qihuibao.utils.CommonUtil
import com.example.qihuibao.utils.LogUtil
import com.example.qihuibao.widget.view.CommonRecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 *@author: cww
 *@desc: type: 0-下载所有数据，1-更新指定数据（人员、订餐、余额等）
 *@date: 5/16/23 10:58 AM
 */
class MultiDownloadDialog(val type:Int = 0, val dismissBack:(done:Boolean)->Unit) : BaseDialogFragment(R.layout.dialog_multi_download, false) {
//    val MEAL_NUM = 5
    val mealIds = arrayOf("01", "02", "03", "04", "05")
    private lateinit var vm: MainViewModel
    private var rvDownload:CommonRecyclerView? = null
    private val faceFiles = mutableListOf<RspQueryFaceFileBean.FaceFile>()
    private var requestCount = 0
    private var downloadOk = false
    private var totalCanteen = 0
    private var canteenSuccessCount = 0
    private var totalMeal = 0
    private var mealSuccessCount = 0
    private var totalFee = 0
    private var feeSuccessCount = 0
    private var orderSuccessCount = 0
    private var paySuccessCount = 0
    private var useSuccessCount = 0
    private val queryList = arrayListOf(
        DownloadItem("查询企业信息", 0),
        DownloadItem("查询部门信息", 0),
        DownloadItem("查询人员信息", 0),
        DownloadItem("查询人脸文件", 0),
        DownloadItem("下载人脸图片", 0),
        DownloadItem("查询餐厅信息", 0),
        DownloadItem("查询订餐明细", 0),
        DownloadItem("查询支付明细", 0),
        DownloadItem("查询取餐明细", 0),
        DownloadItem("查询餐别信息", 0),
        DownloadItem("查询收费标准", 0),
    )

    override fun initView() {
        vm = ViewModelProvider(this).get(MainViewModel::class.java)
        mView?.findViewById<TextView>(R.id.tv_title)?.text = when(type) {
            1 -> "更新信息"
            else -> "下载数据"
        }
        initRecyclerview()
        mView?.findViewById<View>(R.id.iv_ok)?.setOnClickListener {
//            downloadOk = true//todo for test
            dismiss()
        }
        startDownload()
    }

    private fun initRecyclerview() {
        rvDownload = mView?.findViewById(R.id.rv_download)
        rvDownload?.init(
            R.layout.item_connect_icon,
            LinearLayoutManager(context, RecyclerView.VERTICAL, false),
            queryList,
            {parent, pos ->
                parent.findViewById<TextView>(R.id.tv_name).text = queryList[pos].name
                parent.findViewById<ProgressBar>(R.id.pb).progress = queryList[pos].progress
                parent.findViewById<TextView>(R.id.tv_done).text = queryList[pos].status
            }, {
                if (queryList[it].status == "重试") {
                    queryList[it].progress = 0
                    queryList[it].status = "下载中"
                    rvDownload?.adapter?.notifyItemChanged(it)
                    when(queryList[it].name) {
                        "查询企业信息" -> queryEnterpriseInfo(getPosition("查询企业信息")).invoke()
                        "查询部门信息" -> queryDepartmentInfo(getPosition("查询部门信息")).invoke()
                        "查询人员信息" -> {
                            queryEmployInfo(getPosition("查询人员信息"), 1, mutableListOf()).invoke()
                        }
                        "查询人脸文件" -> {
                            queryFaceFile(getPosition("查询人脸文件"), 1, mutableListOf()).invoke()
                        }
                        "下载人脸图片" -> {
                            downloadFaceFile(getPosition("下载人脸图片"), faceFiles)
                        }
                        "查询餐厅信息" -> {
                            if (!Global.rspQueryEnterpriseInfoBean?.CantList.isNullOrEmpty()) {
                                canteenSuccessCount = 0
                                for (item in Global.rspQueryEnterpriseInfoBean!!.CantList!!) {
                                    if (!item.CantID.isNullOrEmpty()) {
                                        queryCanteenInfo(getPosition("查询餐厅信息"), item.CantID).invoke()
                                    }
                                }
                            }
                        }
                        "查询订餐明细" -> {
                            if (!Global.rspQueryEnterpriseInfoBean?.CantList.isNullOrEmpty()) {
                                orderSuccessCount = 0
//                                orderList.clear()
                                for (item in Global.rspQueryEnterpriseInfoBean!!.CantList!!) {
                                    if (!item.CantID.isNullOrEmpty()) {
                                        queryOrderInfo(getPosition("查询订餐明细"), item.CantID, 1, mutableListOf()).invoke()
                                    }
                                }
                            }
                        }
                        "查询支付明细" -> {
                            if (!Global.rspQueryEnterpriseInfoBean?.CantList.isNullOrEmpty()) {
                                paySuccessCount = 0
                                for (item in Global.rspQueryEnterpriseInfoBean!!.CantList!!) {
                                    if (!item.CantID.isNullOrEmpty()) {
                                        queryPayDetail(getPosition("查询支付明细"), item.CantID, 1, mutableListOf()).invoke()
                                    }
                                }
                            }
                        }
                        "查询取餐明细" -> {
                            if (!Global.rspQueryEnterpriseInfoBean?.CantList.isNullOrEmpty()) {
                                useSuccessCount = 0
                                for (item in Global.rspQueryEnterpriseInfoBean!!.CantList!!) {
                                    if (!item.CantID.isNullOrEmpty()) {
                                        queryUseDetail(getPosition("查询取餐明细"), item.CantID, 1, mutableListOf()).invoke()
                                    }
                                }
                            }
                        }
                        "查询套餐信息" -> {
                            if (!Global.rspQueryEnterpriseInfoBean?.CantList.isNullOrEmpty()) {
                                totalMeal = mealIds.size*totalCanteen
                                mealSuccessCount = 0
                                for (item in Global.rspQueryEnterpriseInfoBean!!.CantList!!) {
                                    repeat(mealIds.size) {i ->//ID:01-05
                                        if (!item.CantID.isNullOrEmpty())  {
                                            queryMealInfo(getPosition("查询套餐信息"), item.CantID, mealIds[i]).invoke()
                                        }
                                    }
                                }
                            }
                        }
                        "查询收费标准" -> {
                            if (Global.rspQueryMealInfoBeans?.isNotEmpty() == true) {
                                feeSuccessCount = 0
                                for (meal in Global.rspQueryMealInfoBeans!!) {
                                    if (!meal.FeeList.isNullOrEmpty()) {
                                        totalFee += meal.FeeList.size
                                        for (fee in meal.FeeList) {
                                            if (!meal.CantID.isNullOrEmpty() && !fee.FeeID.isNullOrEmpty()) {
                                                queryFees(getPosition("查询收费标准"), meal.CantID, meal.CantID, fee.FeeID).invoke()
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        )
    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        dismissBack(downloadOk)
    }

    private fun startDownload() {
        requestCount = 0
        if (type == 0) {
            queryEnterpriseInfo(getPosition("查询企业信息")).invoke()
            queryDepartmentInfo(getPosition("查询部门信息")).invoke()
            queryEmployInfo(getPosition("查询人员信息"), 1, mutableListOf()).invoke()
            queryFaceFile(getPosition("查询人脸文件"), 1, mutableListOf()).invoke()
        }else if (type == 1) {
//            queryEmployInfo(getPosition("查询人员信息"), 1, mutableListOf()).invoke()
//            if (Global.currentCanteenInfoBean != null) {
//                //query canteen
//                totalCanteen = 1
//                queryCanteenInfo(getPosition("查询餐厅信息"), Global.currentCanteenInfoBean!!.CantID).invoke()
//                //query order detail
////                orderList.clear()
//                orderSuccessCount = 0
//                queryOrderInfo(getPosition("查询订餐明细"), Global.currentCanteenInfoBean!!.CantID, 1, mutableListOf()).invoke()
//                //query meal
//                totalMeal = mealIds.size*totalCanteen
//                mealSuccessCount = 0
//                repeat(mealIds.size) {i ->//ID:01-05
//                    queryMealInfo(getPosition("查询套餐信息"), Global.currentCanteenInfoBean!!.CantID, mealIds[i]).invoke()
//                }
//            }
            queryEnterpriseInfo(getPosition("查询企业信息")).invoke()
            queryDepartmentInfo(getPosition("查询部门信息")).invoke()
            queryEmployInfo(getPosition("查询人员信息"), 1, mutableListOf()).invoke()
            queryFaceFile(getPosition("查询人脸文件"), 1, mutableListOf()).invoke()
        }
    }

    private fun queryEnterpriseInfo(pos:Int): () -> Unit =  {
        vm.queryEnterpriseInfo().observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    var saved = false
                    withContext(Dispatchers.IO) {
                        try {
                            MyDatabase.db.enterpriseInfoDao().deleteAll()
                            MyDatabase.db.canteenInfoDao().deleteAll()
                            MyDatabase.db.mealInfoDao().deleteAll()
                            MyDatabase.db.feesInfoDao().deleteAll()
                            MyDatabase.db.orderInfoDao().deleteAll()
                            MyDatabase.db.useInfoDao().deleteAll()
                            MyDatabase.db.payInfoDao().deleteAll()
                            val ret = MyDatabase.db.enterpriseInfoDao().save(it)
                            Global.rspQueryEnterpriseInfoBean = it
                            saved = true
                        }catch (e:Exception) { }
                    }
                    if (saved) {
                        queryList[pos].progress = 100
                        queryList[pos].status = "完成"
                        handleResponse()
                        rvDownload?.adapter?.notifyItemChanged(pos)
                        //next
                        if (it.CantList?.isNotEmpty() == true) {
                            //query canteen
                            totalCanteen = it.CantList.size
                            canteenSuccessCount = 0
                            for (item in it.CantList) {
                                if (!item.CantID.isNullOrEmpty())  {
                                    queryCanteenInfo(getPosition("查询餐厅信息"), item.CantID).invoke()
                                }
                            }
                            //query order detail
                            orderSuccessCount = 0
                            for (item in it.CantList) {
                                if (!item.CantID.isNullOrEmpty()) {
                                    queryOrderInfo(getPosition("查询订餐明细"), item.CantID, 1, mutableListOf()).invoke()
                                }
                            }
                            //query pay detail
                            paySuccessCount = 0
                            for (item in it.CantList) {
                                if (!item.CantID.isNullOrEmpty()) {
                                    queryPayDetail(getPosition("查询支付明细"), item.CantID, 1, mutableListOf()).invoke()
                                }
                            }
                            //query use detail
                            useSuccessCount = 0
                            for (item in it.CantList) {
                                if (!item.CantID.isNullOrEmpty()) {
                                    queryUseDetail(getPosition("查询取餐明细"), item.CantID, 1, mutableListOf()).invoke()
                                }
                            }
                            //query meal
                            totalMeal = mealIds.size*totalCanteen
                            mealSuccessCount = 0
                            for (item in it.CantList) {
                                repeat(mealIds.size) {i ->//ID:01-05
                                    if (!item.CantID.isNullOrEmpty()) {
                                        queryMealInfo(getPosition("查询餐别信息"), item.CantID, mealIds[i]).invoke()
                                    }
                                }
                            }
                        }
                    }else {
                        queryList[pos].status = "重试"
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    private fun queryDepartmentInfo(pos:Int): () -> Unit =  {
        vm.queryDepartmentInfo().observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    var saved = false
                    if (it.DepList.isNullOrEmpty()) {
                        saved = true
                    }else {
                        withContext(Dispatchers.IO) {
                            try {
                                MyDatabase.db.departmentInfoDao().deleteAll()
                                val ret = MyDatabase.db.departmentInfoDao().saveList(it.DepList!!)
                                saved = true
                            }catch (e:Exception) { }
                        }
                    }
                    if (saved) {
                        queryList[pos].progress = 100
                        queryList[pos].status = "完成"
                        handleResponse()
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }else {
                        queryList[pos].status = "重试"
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    private fun queryEmployInfo(pos:Int, pageNo:Int, list:MutableList<RspQueryEmployInfoBean.Employ>): () -> Unit =  {
        vm.queryEmployInfo(ReqQueryEmployInfoBean(PageNo = pageNo)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    if (!it.EmpList.isNullOrEmpty()) {
                        list.addAll(it.EmpList!!)
                    }
                    if (it.HasNext == "1") {
                        queryList[pos].progress = pageNo*10
                        rvDownload?.adapter?.notifyItemChanged(pos)
                        queryEmployInfo(pos, pageNo+1, list).invoke()
                    }else {
                        var saved = false
                        withContext(Dispatchers.IO) {
                            try {
                                MyDatabase.db.employInfoDao().deleteAll()
                                MyDatabase.db.employInfoDao().saveList(list)
                                saved = true
                            }catch (e:Exception) { }
                        }
                        if (saved) {
                            queryList[pos].progress = 100
                            queryList[pos].status = "完成"
                            handleResponse()
                        }else {
                            queryList[pos].status = "重试"
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    private fun queryFaceFile(pos:Int, pageNo:Int, list:MutableList<RspQueryFaceFileBean.FaceFile>): () -> Unit =  {
        vm.queryFaceFile(ReqQueryFaceFileBean(PageNo = pageNo)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    if (!it.FaceFileList.isNullOrEmpty()) {
                        list.addAll(it.FaceFileList!!)
                    }
                    if (it.HasNext == "1") {
                        queryList[pos].progress = pageNo*10
                        rvDownload?.adapter?.notifyItemChanged(pos)
                        queryFaceFile(pos, pageNo+1, list).invoke()
                    }else {
                        var saved = false
                        withContext(Dispatchers.IO) {
                            try {
                                MyDatabase.db.faceFileInfoDao().deleteAll()
                                MyDatabase.db.faceFileInfoDao().saveList(list)
                                saved = true
                            }catch (e:Exception) { }
                        }
                        if (saved) {
                            faceFiles.clear()
                            faceFiles.addAll(list)
                            queryList[pos].progress = 100
                            queryList[pos].status = "完成"
                            handleResponse()
                            if (list.isNotEmpty()) {
                                downloadFaceFile(getPosition("下载人脸图片"), list)
                            }else {
                                queryList[getPosition("下载人脸图片")].status = "空"
                                rvDownload?.adapter?.notifyItemChanged(getPosition("下载人脸图片"))
                                handleResponse()
                            }
                        }else {
                            queryList[pos].status = "重试"
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    private fun downloadFaceFile(pos:Int, faces:List<RspQueryFaceFileBean.FaceFile>) {
        var count = 0
        if (!File(Global.facePath).exists()) {
            File(Global.facePath).mkdirs()
        }
        for (item in faces) {
            vm.downloadFaceFile(item).observe(this) {
                if (it.RetCode == "0") {
                    queryList[pos].progress = (++count*1f/faces.size*100).toInt()
                    if (count == faces.size) {
                        queryList[pos].status = "完成"
                        handleResponse()
                    }
                }else {
                    queryList[pos].status = "重试"
                }
                rvDownload?.adapter?.notifyItemChanged(pos)
            }
        }
    }

    //查询餐厅信息(需要企业信息)
    private fun queryCanteenInfo(pos:Int, canteenId:String): () -> Unit =  {
        vm.queryCanteenInfo(ReqQueryCanteenInfoBean(CantID = canteenId)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
//                    canteenSuccessCount++
                    var saved = false
                    withContext(Dispatchers.IO) {
                        try {
                            val ret = MyDatabase.db.canteenInfoDao().save(it)
                            saved = true
                        }catch (e:Exception) { }
                    }
                    if (saved) {
                        queryList[pos].progress = (++canteenSuccessCount*1f/totalCanteen*100).toInt()
                        if (canteenSuccessCount == totalCanteen) {
                            queryList[pos].status = "完成"
                            handleResponse()
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }else {
                        queryList[pos].status = "重试"
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    //查询订餐明细（需要餐厅）
    private fun queryOrderInfo(pos:Int, canteenId:String, pageNo:Int, list:MutableList<RspQueryOrderInfoBean.Order>): () -> Unit =  {
        vm.queryOrderInfo(ReqQueryOrderInfoBean(CantID = canteenId, PageNo = pageNo)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    if (!it.OrderList.isNullOrEmpty()) {
                        list.addAll(it.OrderList!!)
                    }
                    if (it.HasNext == "1") {
                        queryOrderInfo(pos, canteenId, pageNo+1, list).invoke()
                    }else {
                        var saved = false
                        withContext(Dispatchers.IO) {
                            try {
                                for (item in list) {
                                    item.CantID = canteenId
                                }
                                MyDatabase.db.orderInfoDao().saveList(list)
                                saved = true
                            }catch (e:Exception) { }
                        }
                        if (saved) {
                            queryList[pos].progress = (++orderSuccessCount*1f/totalCanteen*100).toInt()
                            if (orderSuccessCount == totalCanteen) {
                                queryList[pos].status = "完成"
                                handleResponse()
                            }
                        }else {
                            queryList[pos].status = "重试"
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    //查询支付明细（需要餐厅）
    private fun queryPayDetail(pos:Int, canteenId:String, pageNo:Int, list:MutableList<RspQueryPayDetailBean.Pay>): () -> Unit =  {
        vm.queryPayDetail(ReqQueryPayDetailBean(CantID = canteenId, PageNo = pageNo)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    if (!it.PayList.isNullOrEmpty()) {
                        list.addAll(it.PayList!!)
                    }
                    if (it.HasNext == "1" && pageNo < 3) {//todo delete pageNo
                        queryPayDetail(pos, canteenId, pageNo+1, list).invoke()
                    }else {
                        var saved = false
                        withContext(Dispatchers.IO) {
                            try {
                                MyDatabase.db.payInfoDao().saveList(list)
                                saved = true
                            }catch (e:Exception) { }
                        }
                        if (saved) {
                            queryList[pos].progress = (++paySuccessCount*1f/totalCanteen*100).toInt()
                            if (paySuccessCount == totalCanteen) {
                                queryList[pos].status = "完成"
                                handleResponse()
                            }
                        }else {
                            queryList[pos].status = "重试"
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    //查询取餐明细（需要餐厅）
    private fun queryUseDetail(pos:Int, canteenId:String, pageNo:Int, list:MutableList<RspUseDetailBean.Use>): () -> Unit =  {
        vm.queryUseDetail(ReqUseDetailBean(CantID = canteenId, PageNo = pageNo)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    if (!it.UseList.isNullOrEmpty()) {
                        list.addAll(it.UseList!!)
                    }
                    if (it.HasNext == "1") {
                        queryUseDetail(pos, canteenId, pageNo+1, list).invoke()
                    }else {
                        var saved = false
                        withContext(Dispatchers.IO) {
                            try {
                                MyDatabase.db.useInfoDao().saveList(list)
                                saved = true
                            }catch (e:Exception) { }
                        }
                        if (saved) {
                            queryList[pos].progress = (++useSuccessCount*1f/totalCanteen*100).toInt()
                            if (useSuccessCount == totalCanteen) {
                                queryList[pos].status = "完成"
                                handleResponse()
                            }
                        }else {
                            queryList[pos].status = "重试"
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    //查询餐别信息（需要先选择餐厅）
    private fun queryMealInfo(pos:Int, canteenId:String, mealId:String): () -> Unit =  {
        vm.queryMealInfo(ReqQueryMealInfoBean(CantID = canteenId, MealID = mealId)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    var saved = false
                    withContext(Dispatchers.IO) {
                        try {
                            it.CantID = canteenId
                            val ret = MyDatabase.db.mealInfoDao().save(it)
                            Global.rspQueryMealInfoBeans = MyDatabase.db.mealInfoDao().queryAll()
                            saved = true
                        }catch (e:Exception) { }
                    }
                    if (saved) {
                        queryList[pos].progress = (++mealSuccessCount*1f/totalMeal*100).toInt()
                        if (mealSuccessCount == totalMeal) {
                            queryList[pos].status = "完成"
                            handleResponse()
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                        //next
                        if (mealSuccessCount == 1) {
                            feeSuccessCount = 0
                        }
                        if (!it.FeeList.isNullOrEmpty()) {
                            totalFee += it.FeeList.size
                            for (fee in it.FeeList) {
                                if (!fee.FeeID.isNullOrEmpty()) {
                                    queryFees(getPosition("查询收费标准"), canteenId, mealId, fee.FeeID).invoke()
                                }
                            }
                        }else {
                            queryList[getPosition("查询收费标准")].status = "空"
                            rvDownload?.adapter?.notifyItemChanged(getPosition("查询收费标准"))
                            handleResponse()
                        }
                    }else {
                        queryList[pos].status = "重试"
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    //查询套餐收费标准（需要套餐信息）
    private fun queryFees(pos:Int, canteenId:String, mealId:String, feeId:String): () -> Unit =  {
        vm.queryFees(ReqQueryFeesBean(CantID = canteenId, MealID = mealId, FeeID = feeId)).observe(this) {
            lifecycleScope.launch {
                if (it.RetCode == "0") {
                    var saved = false
                    withContext(Dispatchers.IO) {
                        try {
//                            LogUtil.e("queryFees: $canteenId, $mealId, $feeId")
                            it.CantID = canteenId
                            it.MealID = mealId
                            it.FeeID = feeId
                            val ret = MyDatabase.db.feesInfoDao().save(it)
                            saved = true
                        }catch (e:Exception) { }
                    }
                    if (saved) {
                        queryList[pos].progress = (++feeSuccessCount*1f/totalFee*100).toInt()
                        if (feeSuccessCount == totalFee) {
                            queryList[pos].status = "完成"
                            handleResponse()
                        }
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }else {
                        queryList[pos].status = "重试"
                        rvDownload?.adapter?.notifyItemChanged(pos)
                    }
                }else {
                    queryList[pos].status = "重试"
                    rvDownload?.adapter?.notifyItemChanged(pos)
                }
            }
        }
    }

    @Synchronized
    private fun handleResponse() {
        requestCount++
        if (requestCount == queryList.size) {
            // 所有请求都已完成
            downloadOk = true
            dismiss()
        }
    }

    private fun getPosition(name:String) : Int {
        for (i in queryList.indices) {
            if (queryList[i].name == name) {
                return i
            }
        }
        return 0
    }

}